'''
https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
'''
from typing import Optional, List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        cur = -1000000
        cnt = 0
        max_cnt = -1
        def f(root):
            if root is None: return
            f(root.left)
            # ======
            nonlocal cnt, cur, max_cnt, res
            if root.val == cur:
                cnt += 1
            else:
                cur = root.val
                cnt = 1
            if cnt == max_cnt:
                res.append(cur)
            elif cnt > max_cnt:
                max_cnt = cnt
                res = [cur]
            # ======
            f(root.right)
        f(root)
        return res

root = TreeNode(0)
print(Solution().findMode(root))